<template>
  <div class="notice">
    <el-space>
      <el-select placeholder="请选择" v-model="status">
        <el-option :value="item.value" :label="item.label" v-for="item in selectStatus" :key="item.value" />
      </el-select>
      <el-select placeholder="请选择" v-model="type">
        <el-option :value="item.value" :label="item.name" v-for="item in adTypeMap" :key="item.value" />
      </el-select>
      <el-button type="primary" :icon="Search" @click="initData()" v-btnkey='"promotion:advert:list"' size='default'>查找</el-button>
      <el-button type="primary" :icon="Plus" @click="operation(1)" v-btnkey='"promotion:advert:create"' size='default'>添加</el-button>
    </el-space>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%;margin-top:10px" border :header-cell-style="{'text-align':'center'}" :cell-style="{'text-align':'center'}">
      <el-table-column label="广告ID" prop="id">
      </el-table-column>
      <el-table-column label="广告标题" prop="title">
      </el-table-column>
      <el-table-column label="广告图片" prop="imgUrl" width="150">
        <template #default="scope">
          <el-popover placement="right" :width="500" trigger="hover" v-if="scope.row.type<6">
            <div style=" text-align:center">
              <el-image :src='scope.row.imgUrl' />
            </div>
            <template #reference>
              <el-image :src='scope.row.imgUrl' fit='fill' />
            </template>
          </el-popover>
          <el-tag v-else>此类型不需要图片</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告类型" prop="type">
        <template #default="scope">
          <el-tag>
            {{logType(scope.row.type,adTypeMap)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="广告状态">
        <template #default="scope">
          <el-tag>
            {{scope.row.status?'激活':'冻结'}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="类型关联" prop="unionType">
        <template #default="scope">
          <el-tag>
            {{logType(scope.row.unionType,adUnionTypeMap)}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="关联[ID]" prop="unionValue">
      </el-table-column>
      <el-table-column label="创建时间" prop="gmtCreate">
        <template #default="scope">
          {{new Date(scope.row.gmtCreate).friendTime()}}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template #default="scope">
          <el-button size="small" type="primary" v-btnkey='"promotion:advert:edit"'  @click="operation(0, scope.row)">编辑</el-button>
          <el-button size="small" type="danger"  v-btnkey='"promotion:advert:delete"' @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Paging v-bind="pageData" @pageChang="pageChang"></Paging>
    <!-- 弹出框 -->
    <el-dialog v-model="dialogFormVisible" :title="title?'添加':'修改'" :destroy-on-close='true'>
      <el-form :model="form" :rules='rules' ref="formRef">
        <el-form-item label="广告标题" prop='title' :label-width="formLabelWidth">
          <el-input v-model="form.title" autocomplete="off" />
        </el-form-item>
        <el-form-item label="广告类型" :label-width="formLabelWidth" prop='type'>
          <el-select placeholder="请选择" v-model="form.type">
            <el-option :label="item.name" :value="item.value" v-for="(item,index) in adTypeMap" :key="item.value" @click="option(item,index)" />
          </el-select>
        </el-form-item>
        <el-form-item id="bag" label='广告图片' :style="'background-color:'+form.color" :label-width="formLabelWidth" v-if="adTypeMap.find(item=>item.value==form.type)?.picRequire">
          <el-upload :show-file-list='false' class="avatar-uploader" :before-upload="beforeAvatarUpload" :headers='myHeaders' :on-success="handleAvatarSuccess" :action="imgPath">
            <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label='广告状态' :label-width="formLabelWidth" prop='status'>
          <el-switch v-model="form.status" :active-value='1' :inactive-value='0' />
        </el-form-item>
        <el-form-item label='关联类型' :label-width="formLabelWidth" prop='unionType'>
          <el-select placeholder="点击跳转目标" v-model="form.unionType" @change="(e)=>{indTyp=e}">
            <el-option :value="item.value" :label="item.name" v-for="(item) in adUnionTypeMap" :key="item.value" :disabled='arr.indexOf(item.value)==-1' />
          </el-select>
        </el-form-item>
        <el-form-item :label='adUnionTypeMap[indTyp-1].name' :label-width="formLabelWidth" v-if="indTyp" prop='unionValue'>
          <el-cascader v-model="form.unionValue" :options="commodity" :props="{emitPath:false,value:'id'}" placeholder="关联至商品" v-if="indTyp==1" />
          <el-cascader v-model="form.unionValue" :options="category" :props="part" placeholder="关联至类目" v-else-if="indTyp==2" />
          <el-input placeholder="点击广告后，用户将得到“此关键字”的商品搜索" v-model="form.unionValue" v-else-if="indTyp==3" />
          <el-select placeholder="请选择一个功能页面" v-model="form.unionValue" v-else>
            <el-option :value="item.value" :label="item.name" v-for="item in functionPage" :key='item.value' />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="confirm('formRef')">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { Search, Plus } from '@element-plus/icons-vue';
import Paging from "@/components/Paging/Paging.vue";
import { post, imgUrl } from "@/utils/http";
import { show } from "@/utils/averageColor";
var token = Cookies.get('token') // 获取token
export default {
  setup() {
    return {
      Search,
      Plus
    }
  },
  components: { Paging, Plus },
  data() {
    return {
      name: 'Notice',
      status: '', //搜索状态
      type: '',  //搜索类型
      selectStatus: [{ label: '激活', value: 1 }, { label: '冻结', value: 0 }],
      adTypeMap: [
        { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: "轮播" },
        { value: 2, unionTypes: [2], picRequire: true, name: "分类精选" },
        { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: "横幅" },
        { value: 4, unionTypes: [1, 2, 3, 4], picRequire: true, name: "首页轮播下5按钮" },
        { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: "公告" },
        { value: 9, unionTypes: [1], picRequire: false, name: "商品推荐" }
      ],
      adUnionTypeMap: [
        { value: 1, name: "商品" },
        { value: 2, name: "类目" },
        { value: 3, name: "关键字" },
        { value: 4, name: "功能页面" },
      ],
      tableData: [],  //表格
      pageData: {  //分页数据
        total: 0,
        currentPage: 1,
        pageSize: 10
      },
      dialogFormVisible: false, //弹出框显示
      formLabelWidth: '140px',
      form: {  //添加数据
        title: '',
        type: '',
        unionType: '',
        status: 1,
        unionValue: '',
        imgUrl: '',
        color: ''
      },
      id: 0,
      myHeaders: { AdminToken: token },  //图片上传请求头
      imgPath: imgUrl,   //图片地址
      ind: 0,  //类型下标
      title: false,  //弹出框标题
      indTyp: 0,  //关联类型下标
      commodity: [],  //商品
      category: [],  //类目
      part: {  //类目子集数据
        label: 'title',
        value: 'id',
        children: 'childrenList',
        emitPath: false,  //选择最后一位子节点
      },
      rules: {  //验证
        title: [{ required: true, message: "请输入标题", trigger: 'blur' }],
        type: [{ required: true, message: "请选择", trigger: 'blur' }],
        status: [{ required: true, message: "请选择", trigger: 'blur' }],
        unionType: [{ required: true, message: "请选择", trigger: 'blur' }],
        unionValue: [{ required: true, message: "请选择", trigger: 'blur' }]
      },
      // 功能页面
      functionPage: [
        { value: '/index/commodity/group', name: '团购列表' },
        { value: '/index/promotion/coupon', name: '优惠券列表' }
      ],
      arr: []  //关联类型判断
    }
  },
  methods: {
    // 初始化数据
    initData() {
      post({ _gp: 'admin.advert', _mt: 'list', type: this.type, status: this.status, pageNo: this.pageData.currentPage, limit: this.pageData.pageSize }).then(res => {
        if (200 == res.errno) {
          this.tableData = res.data.items
          this.pageData.total = res.data.total
        }
      })
    },
    // 类型表格数据
    logType(type, arr) {
      return arr.find(item => item.value == type).name
    },
    // 选择类型
    option(item, index) {
      this.ind = index
      this.arr = item.unionTypes
    },
    // 关联数据
    relevanceData() {
      post({ _gp: 'admin.product', _mt: 'getSpuBigTree' }).then(res => {
        this.commodity = res.data
      })
      post({ _gp: 'admin.category', _mt: 'categoryTree' }).then(res => {
        this.category = res.data
      })
    },
    // 添加 或修改
    operation(num, row) {
      if (this.category == '') { this.relevanceData() }  //数据只加载一次
      this.title = num
      this.dialogFormVisible = true
      if (num) return Object.assign(this.form, this.$options.data().form)  //给表单赋上初始值
      this.id = row.id
      this.indTyp = row.unionType  //隐藏显示用
      Object.assign(this.form, row)
      if (this.form.unionType == 1 || this.form.unionType == 2) {
        this.form.unionValue = Number(row.unionValue)
      }
    },
    // 确定
    confirm(formEl) {
      this.$refs[formEl].validate(valid => {
        if (valid) {
          if (this.title) {  //添加
            if (!this.form.imgUrl) this.form.imgUrl = 'https://www.baidu.com/img/flexible/logo/pc/result.png'
            post({ _gp: 'admin.advert', _mt: 'create', ...this.form }).then(res => {
              if (200 == res.errno) {
                this.dialogFormVisible = false
                ElMessage.success('成功')
                this.initData()
              }
            })
          } else {
            let data = { _gp: 'admin.advert', _mt: 'edit', adId: this.id, ...this.form }
            post(data).then(res => {
              this.dialogFormVisible = false
              ElMessage.success('成功')
              this.initData()
            })
          }
        }
      })
    },
    // 删除
    handleDelete(row) {
      ElMessageBox.confirm(
        '确定要删除吗?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(() => {
          post({ _gp: 'admin.advert', _mt: 'delete', type: row.type, adId: row.id }).then(res => {
            if (200 == res.errno) {
              ElMessage.success('成功')
              this.initData()
            } else {
              ElMessage.warning(res.errmsg)
            }
          })
        })
    },
    // 分页方法
    pageChang(e) {
      Object.assign(this.pageData, e)
      this.initData()
    },
    // 上传图片
    handleAvatarSuccess(res, file) {
      show(URL.createObjectURL(file.raw), (color) => {  //使用封装的背景色
        this.form.color = color
      })
      if (200 == res.errno) return this.form.imgUrl = file.response.url  //赋值图片路径
    },
    beforeAvatarUpload(rawFile) {
      if (rawFile.type !== 'image/jpeg') {
        ElMessage.error('图片得是jpg类型!')
        return false
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('头像图片不能超过2MB!')
        return false
      }
      return true
    }
  },
  created() {
    this.initData()
  }
}
</script>

<style lang="less" scoped>
.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 130px;
  height: 120px;
  border: 1px #ccc dashed;
}
.avatar-uploader .avatar {
  width: 150px;
}
/deep/.el-overlay {
  z-index: 5 !important;
}
</style>